<template>
	<div class="system-role-container layout-padding">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form ref="queryForm" :inline="true">
				<el-form-item label="租户名称">
					<el-input v-model="state.tableParams.name" placeholder="租户名称" clearable />
				</el-form-item>
				<el-form-item label="联系电话">
					<el-input v-model="state.tableParams.phone" placeholder="联系电话" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="ele-Plus" @click="openAddTenant('add')"> 新增 </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 8px">
			<el-table :data="state.tenantData" style="width: 100%" v-loading="state.loading" border>
				<el-table-column type="index" label="序号" width="70" align="center" fixed />
				<el-table-column prop="name" label="租户名称" width="160" align="center" show-overflow-tooltip />
				<el-table-column prop="adminAccount" label="租管账号" align="center" width="120" show-overflow-tooltip />
				<el-table-column prop="phone" label="电话" width="120" align="center" show-overflow-tooltip />
				<!-- <el-table-column prop="host" label="主机" show-overflow-tooltip /> -->
				<!-- <el-table-column prop="email" label="邮箱" show-overflow-tooltip /> -->
				<el-table-column prop="tenantType" label="租户类型" width="100" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.tenantType === 0"> ID隔离 </el-tag>
						<el-tag type="danger" v-else> 库隔离 </el-tag>
					</template>
				</el-table-column>
				<el-table-column label="状态" width="70" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" size="small" @change="changeStatus(scope.row)" :disabled="scope.row.id == 123456780000000" />
					</template>
				</el-table-column>
				<el-table-column prop="dbType" label="数据库类型" width="120" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.dbType === 0"> MySql </el-tag>
						<el-tag v-else-if="scope.row.dbType === 1"> SqlServer </el-tag>
						<el-tag v-if="scope.row.dbType === 2"> Sqlite </el-tag>
						<el-tag v-else-if="scope.row.dbType === 3"> Oracle </el-tag>
						<el-tag v-if="scope.row.dbType === 4"> PostgreSQL </el-tag>
						<el-tag v-else-if="scope.row.dbType === 5"> Dm </el-tag>
						<el-tag v-if="scope.row.dbType === 6"> Kdbndp </el-tag>
						<el-tag v-else-if="scope.row.dbType === 7"> Oscar </el-tag>
						<el-tag v-if="scope.row.dbType === 8"> MySqlConnector </el-tag>
						<el-tag v-else-if="scope.row.dbType === 9"> Access </el-tag>
						<el-tag v-if="scope.row.dbType === 10"> OpenGauss </el-tag>
						<el-tag v-else-if="scope.row.dbType === 11"> QuestDB </el-tag>
						<el-tag v-else-if="scope.row.dbType === 12"> HG </el-tag>
						<el-tag v-else-if="scope.row.dbType === 13"> ClickHouse </el-tag>
						<el-tag v-else-if="scope.row.dbType === 14"> GBase </el-tag>
						<el-tag v-else-if="scope.row.dbType === 900"> Custom </el-tag>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="configId" label="数据库标识" show-overflow-tooltip /> -->
				<el-table-column prop="connection" label="数据库连接" min-width="300" header-align="center" show-overflow-tooltip />
				<el-table-column prop="slaveConnections" label="从库连接" min-width="300" header-align="center" show-overflow-tooltip />
				<el-table-column prop="orderNo" label="排序" width="70" align="center" show-overflow-tooltip />
				<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-popover placement="bottom" width="280" trigger="hover">
							<template #reference>
								<el-text type="primary">
									<el-icon><ele-InfoFilled /></el-icon>详情
								</el-text>
							</template>
							<el-descriptions direction="vertical" :column="2" border>
								<el-descriptions-item width="140">
									<template #label>
										<el-text>
											<el-icon><ele-UserFilled /></el-icon>创建者
										</el-text>
									</template>
									<el-tag>{{ scope.row.createUserName ?? '无' }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item>
									<template #label>
										<el-text>
											<el-icon><ele-Calendar /></el-icon>创建时间
										</el-text>
									</template>
									<el-tag>{{ scope.row.createTime ?? '无' }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item>
									<template #label>
										<el-text>
											<el-icon><ele-UserFilled /></el-icon>修改者
										</el-text>
									</template>
									<el-tag>{{ scope.row.updateUserName ?? '无' }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item>
									<template #label>
										<el-text>
											<el-icon><ele-Calendar /></el-icon>修改时间
										</el-text>
									</template>
									<el-tag>{{ scope.row.updateTime ?? '无' }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item>
									<template #label>
										<el-text>
											<el-icon><ele-Tickets /></el-icon>备注
										</el-text>
									</template>
									{{ scope.row.remark }}
								</el-descriptions-item>
							</el-descriptions>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Coin" size="small" text type="danger" @click="createTenant(scope.row)" :disabled="scope.row.tenantType == 0"> 创建库 </el-button>
						<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditTenant('edit', scope.row)"> 编辑 </el-button>
						<el-dropdown>
							<el-button icon="ele-MoreFilled" size="small" text type="primary" style="padding-left: 12px" />
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item icon="ele-OfficeBuilding" @click="openGrantMenu(scope.row)"> 授权菜单 </el-dropdown-item>
									<el-dropdown-item icon="ele-RefreshLeft" @click="resetTenantPwd(scope.row)" > 重置密码 </el-dropdown-item>
									<el-dropdown-item icon="ele-Delete" @click="delTenant(scope.row)" > 删除租户 </el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.pageIndex"
				v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total"
				:page-sizes="[10, 20, 50, 100]"
				small
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
			/>
		</el-card>

		<tenantDialog ref="editTenantRef" :title="state.editTenantTitle" @handleQuery="handleQuery" />
		<grantMenuDialog ref="grantMenuRef" />

	</div>
</template>

<script setup lang="ts" name="systemTenant">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useTenantApi } from '/@/api/tenant';

// import EditTenant from '/@/views/system/tenant/component/editTenant.vue';
// import GrantMenu from '/@/views/system/tenant/component/grantMenu.vue';

// 引入组件
// const PosDialog = defineAsyncComponent(() => import('/@/views/system/pos/dialog.vue'));
const tenantDialog = defineAsyncComponent(() => import('/@/views/system/tenant/dialog.vue'));
const grantMenuDialog = defineAsyncComponent(() => import('/@/views/system/tenant/grantMenu.vue'));

// 定义变量内容
// onst posDialogRef = ref();
const editTenantRef = ref();
const grantMenuRef = ref();
// const grantMenuRef = ref<InstanceType<typeof GrantMenu>>();

const state = reactive({
	loading: false,
	tenantData: [] as Array<TenantItem>,
	tableParams: {
		name: undefined,
		phone: undefined,
		pageIndex: 1,
		pageSize: 20,
		total: 0 as any,
	},
	editPosTitle: '',
});

onMounted(async () => {
	handleQuery();
});

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	//let params = Object.assign(state.tableData.param);
	useTenantApi().tenantPageList(state.tableParams).then(async (res: AjaxResult)=>{
		const _data : Array<TenantItem> = res.data.items;
		//console.log('ok-res:'+JSON.stringify(res.data));
		state.tenantData = _data; //JSON.parse(JSON.stringify(res.data));
		state.tableParams.total = res.data?.total;

		setTimeout(() => {
			state.loading = false;
		}, 500);
	});


	// state.loading = true;
	// let params = Object.assign(state.queryParams, state.tableParams);
	// var res = await getAPI(SysRoleApi).apiSysRolePagePost(params);
	// state.roleData = res.data.result?.items ?? [];
	// state.tableParams.total = res.data.result?.total;
	// setTimeout(() => {
	// 	state.loading = false;
	// }, 500);
};

// 重置操作
const resetQuery = () => {
	state.tableParams.name = '';
	state.tableParams.code = '';
	handleQuery();
};

// // 打开新增页面
// const openAddPos = async(type:string) => {
// 	state.editPosTitle = '添加职位';
// 	const _row : PosForm = {status: 0, orderNo: 100 }
// 	posDialogRef.value.openDialog(type, _row);
// };

// // 打开编辑页面
// const openEditPos = async (type: string, row: Object) => {
// 	state.editPosTitle = '编辑职位';
// 	posDialogRef.value?.openDialog(type, row);
// };


// // 删除角色
// const onRowDel = (row: PosForm) => {
// 	ElMessageBox.confirm(`此操作将永久删除职位名称：“${row.name}”，是否继续?`, '提示', {
// 		confirmButtonText: '确认',
// 		cancelButtonText: '取消',
// 		type: 'warning',
// 	})
// 	.then(async () => {
// 		await usePosApi().deletePos({ id: row.id }).then(async (res:AjaxResult) => {
// 			ElMessage.success('删除成功');
// 			handleQuery();
// 		});
// 	})
// 	.catch(() => {});
// };

// 打开新增页面
const openAddTenant = (type:string) => {
	state.editTenantTitle = '添加租户';
	const _row : TenantForm = {tenantType: 0, status: 0, orderNo: 100 }
	editTenantRef.value?.openDialog(type,_row);
};

// 打开编辑页面
const openEditTenant = (type: string, row: Object) => {
	state.editTenantTitle = '编辑租户';
	editTenantRef.value?.openDialog(type, row as TenantForm);
};

// 打开授权菜单页面
const openGrantMenu = async (row: any) => {
	grantMenuRef.value?.openDialog(row);
};

// 重置密码
const resetTenantPwd = async (row: any) => {
	ElMessageBox.confirm(`确定重置密码：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
	.then(async () => {
		await useTenantApi().resetTenantPwd({ userId: row.userId }).then(async (res:AjaxResult)=>{
			ElMessage.success(`密码重置成功为：${res.data.result}`);
		});
	})
	.catch(() => {});
};

// 删除
const delTenant = (row: any) => {
	ElMessageBox.confirm(`确定删除租户：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
	.then(async () => {
		await useTenantApi().deleteTenant({ id: row.id })
		.then(() => {
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {
			
		});
	})
	.catch(() => {});
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.pageIndex = val;
	handleQuery();
};

// 创建租户库
const createTenant = (row: any) => {
	ElMessageBox.confirm(`确定创建/更新租户数据库：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
	.then(async () => {
		await useTenantApi().createTenantDb({ id: row.id })
		.then(() => {
			ElMessage.success('创建/更新租户数据库成功');
		})
		.catch(() => {
			
		});
	})
	.catch(() => {});
};

// 修改状态
const changeStatus = async (row: any) => {
	await useTenantApi().changeTenantState({ id: row.id, status: row.status })
	.then(() => {
		ElMessage.success('租户状态设置成功');
	})
	.catch(() => {
		row.status = row.status == 1 ? 2 : 1;
	});
};

</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
</style>
